package com.zhugang.week06;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @program algorithms
 * @description: levelOrderGroup
 * @author: chanzhugang
 * @create: 2022/07/15 15:25
 */
public class LevelOrderGroup {

    /**
     * 102 二叉树的层序遍历
     *
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        // 队列实现：记录每个节点的层号
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNodeWithLevel> queue = new LinkedList<>();
        queue.add(new TreeNodeWithLevel(root, 0));
        while (!queue.isEmpty()) {
            TreeNodeWithLevel tl = queue.poll();
            if (tl.level > result.size() - 1) {
                // 扩容
                result.add(new ArrayList<>());
            }
            result.get(tl.level).add(tl.node.val);
            if (tl.node.left != null) {
                queue.add(new TreeNodeWithLevel(tl.node.left, tl.level + 1));
            }
            if (tl.node.right != null) {
                queue.add(new TreeNodeWithLevel(tl.node.right, tl.level + 1));
            }
        }
        return result;
    }

    public class TreeNodeWithLevel {
        TreeNode node;
        int level;

        public TreeNodeWithLevel(TreeNode node, int level) {
            this.node = node;
            this.level = level;
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}